<script setup>
import { ref, onMounted, watch } from 'vue';
import { Search, User, Comment, View, Star, Share, More } from '@element-plus/icons-vue';
import { useRouter, useRoute } from 'vue-router';
import { useUserStore } from '../stores/user';
import Header from '../components/Header.vue';
import { getCommunityCategories, createCommunityArticle, getCommunityArticles, getCommunityArticlesByCategory } from '@/api/community'
import { ElMessage } from 'element-plus';
import { uploadFile } from '@/api/common'

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

// 通过props接收是否自动打开发文章弹窗
const props = defineProps({
  showPostDialog: {
    type: Boolean,
    default: false
  }
});

// 话题列表
const topicList = ref([]);

// 帖子类型切换
const activeType = ref('recommend');

// 帖子列表
const postList = ref([
  {
    id: 1,
    title: '前端开发学习路线及推荐资源',
    content: '作为一名前端开发者，我想分享一下我的学习路线和一些非常有用的学习资源。首先，掌握HTML、CSS和JavaScript的基础是非常重要的...',
    author: {
      name: '前端大牛',
      avatar: 'https://via.placeholder.com/40/3d8aff/ffffff?text=FE'
    },
    createTime: '2023-12-15',
    views: 1256,
    likes: 328,
    comments: 56,
    tags: ['前端开发', 'HTML', 'CSS', 'JavaScript']
  },
  {
    id: 2,
    title: 'Vue3和React18哪个更适合2024年的项目？',
    content: '随着Vue3和React18的稳定版本发布，很多开发者在项目选型时都面临着这个选择。本文将从性能、生态、上手难度等多个角度进行对比...',
    author: {
      name: '框架爱好者',
      avatar: 'https://via.placeholder.com/40/41b883/ffffff?text=Vue'
    },
    createTime: '2023-12-20',
    views: 2304,
    likes: 567,
    comments: 124,
    tags: ['Vue', 'React', '前端框架']
  },
  {
    id: 3,
    title: 'Node.js性能优化实践总结',
    content: '在使用Node.js开发高性能应用时，有很多优化技巧可以显著提升应用性能。本文将分享一些在实际项目中经过验证的优化方法...',
    author: {
      name: '后端老司机',
      avatar: 'https://via.placeholder.com/40/539e43/ffffff?text=Node'
    },
    createTime: '2023-12-22',
    views: 1876,
    likes: 432,
    comments: 87,
    tags: ['Node.js', '性能优化', '后端']
  },
  {
    id: 4,
    title: '使用TypeScript提升代码质量的10个技巧',
    content: 'TypeScript作为JavaScript的超集，为我们提供了许多提升代码质量的工具和特性。本文将分享10个在实际项目中能够显著提升代码质量的TypeScript技巧...',
    author: {
      name: 'TS爱好者',
      avatar: 'https://via.placeholder.com/40/007acc/ffffff?text=TS'
    },
    createTime: '2023-12-25',
    views: 1542,
    likes: 389,
    comments: 76,
    tags: ['TypeScript', '代码质量', '最佳实践']
  },
  {
    id: 5,
    title: '2024年最值得学习的编程语言',
    content: '随着技术的不断发展，编程语言的热度也在不断变化。本文将基于就业市场、社区活跃度、发展趋势等因素，分析2024年最值得学习的编程语言...',
    author: {
      name: '技术观察员',
      avatar: 'https://via.placeholder.com/40/ff7d3d/ffffff?text=Tech'
    },
    createTime: '2023-12-28',
    views: 3421,
    likes: 876,
    comments: 213,
    tags: ['编程语言', '技术趋势', '学习路线']
  }
]);

// 发帖弹窗相关
const showPostDialog = ref(props.showPostDialog)
const postForm = ref({
  title: '',
  content: '',
  summary: '',
  coverImage: '',
  images: '',
  categoryId: '',
  status: 1 // 默认已发布
})
const postLoading = ref(false)

// 文章分页数据
const articleList = ref([])
const articleTotal = ref(0)
const articlePage = ref(1)
const articlePageSize = ref(5)
const articleCategoryId = ref('')
const activeCategoryId = ref(null)

// 监听props变化
watch(() => props.showPostDialog, (newVal) => {
  showPostDialog.value = newVal;
});

// 返回首页
const goToHome = () => {
  router.push('/');
};

// 发帖子
const handleCreatePost = () => {
  if (!userStore.isLoggedIn) {
    router.push('/login');
    return;
  }
  showPostDialog.value = true;
};

// 关注用户
const followUser = (userId) => {
  if (!userStore.isLoggedIn) {
    router.push('/login');
    return;
  }
  console.log('关注用户:', userId);
};

const handlePostSubmit = async () => {
  postLoading.value = true;
  try {
    const res = await createCommunityArticle(postForm.value);
    if (res.code === 0 || res.code === 200) {
      showPostDialog.value = false;
      // 可选：刷新帖子列表
      ElMessage.success('发布成功');
    } else {
      ElMessage.error(res.message || '发布失败');
    }
  } catch (e) {
    ElMessage.error('发布失败');
  } finally {
    postLoading.value = false;
  }
};

// 上传图片
const handleCoverUpload = async (file) => {
  try {
    const res = await uploadFile(file)
    if ((res.code === 0 || res.code === 200) && res.data) {
      postForm.value.coverImage = res.data.url || res.data // 兼容不同后端返回
      ElMessage.success('图片上传成功')
    } else {
      ElMessage.error(res.message || '图片上传失败')
    }
  } catch (e) {
    ElMessage.error('图片上传失败')
  }
}

// 点击分类加载该分类下所有文章，并刷新所有分类的count
const handleCategoryClick = async (topic) => {
  activeCategoryId.value = topic.id
  articleCategoryId.value = topic.id
  articlePage.value = 1
  
  try {
    // 使用新接口获取分类下文章
    const res = await getCommunityArticlesByCategory({ 
      categoryId: topic.id, 
      page: articlePage.value, 
      pageSize: articlePageSize.value 
    })
    
    if ((res.code === 0 || res.code === 200) && res.data) {
      articleList.value = res.data.records || []
      articleTotal.value = res.data.total || 0
      // 更新当前话题的文章数量
      topic.count = res.data.total || 0
    } else {
      ElMessage.warning('获取分类文章失败')
      articleList.value = []
      articleTotal.value = 0
    }
    
    // 不再同时刷新所有分类的count，而是采用延迟加载策略
    // 可以在用户切换分类时再更新对应分类的数量
  } catch (e) {
    console.error('获取分类文章失败:', e)
    ElMessage.error('获取文章失败，请稍后再试')
    articleList.value = []
    articleTotal.value = 0
  }
}

// 加载文章列表
const loadArticles = async () => {
  const params = {
    page: articlePage.value,
    pageSize: articlePageSize.value
  }
  if (articleCategoryId.value) params.categoryId = articleCategoryId.value
  const res = await getCommunityArticles(params)
  if ((res.code === 0 || res.code === 200) && res.data) {
    articleList.value = res.data.records || []
    articleTotal.value = res.data.total || 0
  }
}

// 分类筛选
const handleCategorySelect = (catId) => {
  articleCategoryId.value = catId
  articlePage.value = 1
  loadArticles()
}

// 分页切换
const handleArticlePageChange = (page) => {
  articlePage.value = page
  loadArticles()
}
const handleArticleSizeChange = (size) => {
  articlePageSize.value = size
  articlePage.value = 1
  loadArticles()
}

// 查看文章详情
const viewArticleDetail = (id) => {
  router.push(`/community/article/${id}`)
}

// 新增：查看全部话题，显示全部文章
const handleShowAllTopics = () => {
  activeCategoryId.value = null
  articleCategoryId.value = ''
  articlePage.value = 1
  loadArticles()
}

onMounted(async () => {
  // 如果是从/community/create路由进入，自动打开发布弹窗
  if (route.path === '/community/create') {
    showPostDialog.value = true;
  }
  
  // 同步token状态
  const localToken = localStorage.getItem('token');
  if (localToken && userStore.token !== localToken) {
    console.log('同步token状态');
    userStore.setToken(localToken);
    
    // 如果需要，也可以同步用户信息
    try {
      const userInfoStr = localStorage.getItem('userInfo');
      if (userInfoStr) {
        const userInfoData = JSON.parse(userInfoStr);
        userStore.setUserInfo(userInfoData);
      }
    } catch (e) {
      console.error('同步用户信息失败:', e);
    }
  }
  
  // 先确保用户登录状态稳定，防止token竞争
  await new Promise(resolve => setTimeout(resolve, 100));
  
  // 使用Promise.all按顺序处理请求，且添加错误处理
  try {
    // 第一步：获取分类（这个请求可能不需要认证）
    const categoriesPromise = getCommunityCategories().catch(err => {
      console.error('获取分类失败:', err);
      return { code: -1, data: [] };
    });
    
    // 第二步：获取文章，这里不使用await，让两个请求并行但有序处理错误
    const articlesPromise = getCommunityArticles({ 
      page: articlePage.value, 
      pageSize: articlePageSize.value 
    }).catch(err => {
      console.error('获取文章失败:', err);
      return { code: -1, data: { records: [], total: 0 } };
    });
    
    // 等待所有请求完成
    const [categoriesRes, articlesRes] = await Promise.all([
      categoriesPromise,
      articlesPromise
    ]);
    
    // 处理分类结果
    if ((categoriesRes.code === 0 || categoriesRes.code === 200) && categoriesRes.data) {
      topicList.value = categoriesRes.data || [];
    }
    
    // 处理文章结果
    if ((articlesRes.code === 0 || articlesRes.code === 200) && articlesRes.data) {
      articleList.value = articlesRes.data.records || [];
      articleTotal.value = articlesRes.data.total || 0;
    }
    
    // 避免批量更新分类数量导致的大量并发请求
    // 如果需要，可以使用setTimeout错开请求
  } catch (e) {
    console.error('页面加载失败:', e);
  }
});
</script>

<template>
  <div class="community-container">
    <Header />
    
    <!-- 内容区域 -->
    <div class="community-content">
      <!-- 社区头部 -->
      <div class="community-header">
        <div class="header-inner">
          <h1 class="community-title">社区</h1>
          <p class="community-desc">分享技术，交流经验，结识志同道合的开发者</p>
          <div class="header-actions">
            <el-input placeholder="搜索帖子、话题或用户" class="search-input">
              <template #prefix>
                <el-icon><search /></el-icon>
              </template>
            </el-input>
            <el-button type="primary" @click="handleCreatePost">发布帖子</el-button>
          </div>
        </div>
      </div>
      
      <el-row :gutter="20">
        <!-- 左侧边栏 -->
        <el-col :span="6">
          <div class="left-sidebar">
            <div class="user-card">
              <div class="not-login" v-if="!userStore.isLoggedIn">
                <p>登录后享受更多功能</p>
                <el-button type="primary" @click="router.push('/login')">登录/注册</el-button>
              </div>
              <!-- 登录后显示用户信息 -->
              <div class="user-info" v-else>
                <el-avatar :size="60" :src="userStore.userInfo.avatar">
                  <el-icon><user /></el-icon>
                </el-avatar>
                <div class="user-detail">
                  <h3>{{ userStore.userInfo.username }}</h3>
                  <p>关注: 0 | 粉丝: 0 | 帖子: 0</p>
                </div>
              </div>
            </div>
            
            <div class="topics-card">
              <div class="card-header">
                <h3>热门话题</h3>
                <el-link @click="handleShowAllTopics">查看全部</el-link>
              </div>
              <ul class="topic-list">
                <li v-for="topic in topicList" :key="topic.id" class="topic-item">
                  <el-button
                    class="topic-name"
                    :type="activeCategoryId === topic.id ? 'primary' : 'text'"
                    size="small"
                    @click="handleCategoryClick(topic)"
                  >
                    # {{ topic.name }}
                  </el-button>
                  <span class="topic-count">{{ topic.count }}</span>
                </li>
              </ul>
            </div>
          </div>
        </el-col>
        
        <!-- 主内容区 -->
        <el-col :span="18">
          <div class="main-content">
            <div class="post-tabs">
              <el-tabs v-model="activeType">
                <el-tab-pane label="推荐" name="recommend"></el-tab-pane>
                <el-tab-pane label="最新" name="latest"></el-tab-pane>
                <el-tab-pane label="热门" name="hot"></el-tab-pane>
                <el-tab-pane label="关注" name="following"></el-tab-pane>
              </el-tabs>
            </div>
            
            <div class="post-list">
              <div v-for="post in articleList" :key="post.id" class="post-item" @click="viewArticleDetail(post.id)" style="cursor:pointer;">
                <div class="post-author">
                  <el-avatar :size="40" :src="post.creatorAvatar"></el-avatar>
                  <div class="author-info">
                    <div class="author-name">{{ post.createUser }}</div>
                    <div class="post-time">{{ post.createTime }}</div>
                  </div>
                </div>
                <div class="post-content">
                  <h2 class="post-title">{{ post.title }}</h2>
                  <p class="post-text">{{ post.summary || post.content }}</p>
                  <div class="post-tags">
                    <el-tag v-if="post.categoryName" size="small" effect="plain">{{ post.categoryName }}</el-tag>
                  </div>
                  <img v-if="post.coverImage" :src="post.coverImage" alt="封面" class="post-cover-image" />
                </div>
                <div class="post-actions">
                  <div class="action-item">
                    <el-icon><view /></el-icon>
                    <span>{{ post.viewCount }}</span>
                  </div>
                  <div class="action-item">
                    <el-icon><comment /></el-icon>
                    <span>{{ post.commentCount }}</span>
                  </div>
                  <div class="action-item">
                    <el-icon><star /></el-icon>
                    <span>{{ post.likeCount }}</span>
                  </div>
                  <div class="action-item">
                    <el-icon><share /></el-icon>
                    <span>分享</span>
                  </div>
                </div>
              </div>
              <el-pagination
                v-if="articleTotal > 0"
                background
                layout="total, sizes, prev, pager, next, jumper"
                :total="articleTotal"
                :current-page="articlePage"
                :page-sizes="[5, 10, 20]"
                :page-size="articlePageSize"
                @size-change="handleArticleSizeChange"
                @current-change="handleArticlePageChange"
                style="margin-top: 20px; display: flex; justify-content: flex-end;"
              />
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    
    <!-- 底部区域 -->
    <footer class="community-footer">
      <p>© 2023 社区 · <el-link @click="goToHome">返回首页</el-link></p>
    </footer>
  </div>

  <!-- 发帖弹窗 -->
  <el-dialog v-model="showPostDialog" title="发布新帖子" width="500px">
    <el-form :model="postForm" label-width="80px">
      <el-form-item label="标题" required>
        <el-input v-model="postForm.title" placeholder="请输入标题" />
      </el-form-item>
      <el-form-item label="内容" required>
        <el-input type="textarea" v-model="postForm.content" placeholder="请输入内容" rows="6" />
      </el-form-item>
      <el-form-item label="摘要">
        <el-input v-model="postForm.summary" placeholder="请输入摘要" />
      </el-form-item>
      <el-form-item label="封面">
        <el-upload
          class="upload-demo"
          action=""
          :http-request="({ file }) => handleCoverUpload(file)"
          :show-file-list="false"
        >
          <el-button type="primary">上传图片</el-button>
        </el-upload>
        <el-input v-model="postForm.coverImage" placeholder="图片URL，可选" style="margin-top: 8px;" />
        <img v-if="postForm.coverImage" :src="postForm.coverImage" alt="封面预览" style="max-width: 100%; margin-top: 8px;" />
      </el-form-item>
      <el-form-item label="分类" required>
        <el-select v-model="postForm.categoryId" placeholder="请选择分类">
          <el-option v-for="cat in topicList" :key="cat.id" :label="cat.name" :value="cat.id" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="showPostDialog = false">取消</el-button>
      <el-button type="primary" :loading="postLoading" @click="handlePostSubmit">发布</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
.community-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4ebf5 100%);
  font-family: 'Inter', 'Source Sans Pro', 'Microsoft YaHei', sans-serif;
}

.community-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 30px 20px 50px;
}

.community-header {
  margin-bottom: 24px;
}

.header-inner {
  background: #fff;
  border-radius: 16px;
  padding: 30px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.07);
  border: 1px solid rgba(229, 231, 235, 0.7);
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.community-title {
  font-size: 28px;
  font-weight: 700;
  color: #2c5dff;
  margin: 0 0 8px;
  position: relative;
}

.community-desc {
  font-size: 16px;
  color: #6b7280;
  margin: 0 0 24px;
  line-height: 1.5;
}

.header-actions {
  display: flex;
  width: 100%;
  gap: 16px;
}

.search-input {
  flex: 1;
}

.left-sidebar {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.user-card, .topics-card {
  background: #fff;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.07);
  border: 1px solid rgba(229, 231, 235, 0.7);
  transition: transform 0.3s, box-shadow 0.3s;
}

.user-card:hover, .topics-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 30px rgba(44, 93, 255, 0.12);
}

.not-login {
  text-align: center;
  padding: 16px 0;
}

.not-login p {
  margin-bottom: 16px;
  color: #6b7280;
}

.user-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.user-detail {
  margin-top: 12px;
}

.user-detail h3 {
  font-size: 18px;
  font-weight: 600;
  color: #2c5dff;
  margin: 0 0 4px;
}

.user-detail p {
  font-size: 14px;
  color: #6b7280;
  margin: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid rgba(229, 231, 235, 0.7);
}

.card-header h3 {
  font-size: 18px;
  font-weight: 600;
  color: #2c5dff;
  margin: 0;
}

.topic-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.topic-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  transition: transform 0.2s;
}

.topic-item:hover {
  transform: translateX(4px);
}

.topic-name {
  font-size: 14px;
}

.topic-count {
  font-size: 13px;
  color: #94a3b8;
  background: #f0f5ff;
  border-radius: 10px;
  padding: 2px 8px;
}

.main-content {
  background: #fff;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.07);
  border: 1px solid rgba(229, 231, 235, 0.7);
}

.post-tabs {
  margin-bottom: 24px;
}

.post-list {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.post-item {
  background: #fff;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
  border: 1px solid rgba(229, 231, 235, 0.7);
  transition: transform 0.3s, box-shadow 0.3s, border-color 0.3s;
}

.post-item:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 30px rgba(44, 93, 255, 0.12);
  border-color: rgba(44, 93, 255, 0.3);
}

.post-author {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.author-info {
  margin-left: 12px;
}

.author-name {
  font-weight: 500;
  color: #2c5dff;
  margin-bottom: 2px;
}

.post-time {
  font-size: 13px;
  color: #94a3b8;
}

.post-content {
  margin-bottom: 16px;
}

.post-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0 0 12px;
  line-height: 1.4;
}

.post-text {
  color: #6b7280;
  margin: 0 0 12px;
  line-height: 1.6;
  font-size: 15px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.post-tags {
  margin-bottom: 16px;
}

.post-cover-image {
  max-width: 100%;
  border-radius: 8px;
  margin-top: 12px;
  max-height: 300px;
  object-fit: cover;
}

.post-actions {
  display: flex;
  gap: 24px;
  padding-top: 16px;
  border-top: 1px solid rgba(229, 231, 235, 0.7);
}

.action-item {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #94a3b8;
  font-size: 14px;
  transition: color 0.2s;
}

.action-item:hover {
  color: #2c5dff;
}

.community-footer {
  text-align: center;
  padding: 20px 0;
  color: #94a3b8;
  margin-top: 30px;
}

/* Element Plus overrides */
:deep(.el-button--primary) {
  background-color: #2c5dff;
  border-color: #2c5dff;
}

:deep(.el-button--primary:hover), 
:deep(.el-button--primary:focus) {
  background-color: #1c4de0;
  border-color: #1c4de0;
}

:deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #2c5dff;
}

:deep(.el-tabs__item.is-active) {
  color: #2c5dff;
}

:deep(.el-tabs__active-bar) {
  background-color: #2c5dff;
}

:deep(.el-link.el-link--primary) {
  color: #2c5dff;
}

:deep(.el-link.el-link--primary:hover) {
  color: #1c4de0;
}

:deep(.el-tag--plain) {
  border-color: #2c5dff20;
  color: #2c5dff;
  background-color: #f0f5ff;
}

/* Dialog styling */
:deep(.el-dialog__header) {
  padding: 20px 24px;
  border-bottom: 1px solid rgba(229, 231, 235, 0.7);
}

:deep(.el-dialog__title) {
  font-weight: 600;
  color: #2c5dff;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.el-dialog__footer) {
  padding: 16px 24px;
  border-top: 1px solid rgba(229, 231, 235, 0.7);
}

/* Responsive adjustments */
@media (max-width: 768px) {
  .header-actions {
    flex-direction: column;
  }
  
  .post-actions {
    flex-wrap: wrap;
    gap: 16px;
  }
}
</style> 